cmake_minimum_required(VERSION 3.10)
project(kmlg VERSION 0.2.0 LANGUAGES C)

set(CMAKE_C_STANDARD 99)

# Build options for交叉编译与单可执行文件场景
option(BUILD_KEY_LED_ONLY "只构建 key_led 可执行文件" OFF)
option(STATIC_LINK "尽量静态链接 key_led（二进制自包含）" OFF)

# 可配置的内置默认参数（将被注入到 app_config.h）
set(APPCFG_DEFAULT_MQTT_HOST        "mqtt.yyzlab.com.cn" CACHE STRING "默认 MQTT 主机")
set(APPCFG_DEFAULT_MQTT_PORT        1883                CACHE STRING "默认 MQTT 端口")
set(APPCFG_DEFAULT_SUB_TOPIC        "1756687933516/AIOTSIM2Device"   CACHE STRING "默认订阅主题")
set(APPCFG_DEFAULT_PUB_TOPIC        "1756687933516/Device2AIOTSIM"   CACHE STRING "默认发布主题")
set(APPCFG_DEFAULT_DEVICE_ID        0                   CACHE STRING "默认设备ID")
set(APPCFG_DEFAULT_LED_SYSFS_NAME   "led2"             CACHE STRING "默认LED sysfs 名称")
set(APPCFG_DEFAULT_TLS_ENABLE       0                   CACHE STRING "默认启用TLS(0/1)")
set(APPCFG_DEFAULT_WS_ENABLE        0                   CACHE STRING "默认启用WebSocket(0/1)")
set(APPCFG_DEFAULT_WS_PATH          "/mqtt"            CACHE STRING "默认WebSocket路径")

# 生成可配置的 app_config.h（优先于源码 include/）
configure_file(
    ${CMAKE_CURRENT_SOURCE_DIR}/include/app_config.h.in
    ${CMAKE_BINARY_DIR}/generated/app_config.h
    @ONLY
)

# Include headers（将生成目录放在最前，覆盖同名头文件）
include_directories(BEFORE ${CMAKE_BINARY_DIR}/generated)
include_directories(include)

# Common libraries
add_library(gpio_util
    src/gpio.c
    src/led_gpio.c
)
target_link_libraries(gpio_util gpiod)

add_library(device_fan
    src/fan.c
)
target_link_libraries(device_fan gpiod)

add_library(device_sensor
    src/sensor.c
)
target_link_libraries(device_sensor m)

# ADC (电压/电流)
add_library(device_adc
    src/adc.c
)
target_link_libraries(device_adc m)

# 数字量输入（按键/红外/火焰/光电）
add_library(device_digital
    src/digital.c
)
target_link_libraries(device_digital gpio_util)

# LED via sysfs
add_library(led_sysfs
    src/led_sysfs.c
)

# Beeper via input event
add_library(device_beeper
    src/beeper.c
)

# Bundle cJSON from source to avoid external dependency
add_library(cjson
    src/cJSON.c
)
target_include_directories(cjson PUBLIC src)

# MQTT utility module (wrapper around libmosquitto)
add_library(mqtt_util
    src/mqtt_client.c
)
target_link_libraries(mqtt_util mosquitto)

# Apps: key with LED control + MQTT
add_executable(key_led
    apps/key_led.c
)
target_link_libraries(key_led gpio_util device_fan device_sensor device_adc device_digital led_sysfs device_beeper gpiod mqtt_util cjson)

# 交叉编译场景下可选静态链接（需要工具链和依赖库均提供静态库）
if(STATIC_LINK)
    if (CMAKE_C_COMPILER_ID MATCHES "GNU|Clang")
        target_link_options(key_led PRIVATE -static)
    endif()
endif()

# 仅在需要时构建辅助工具
if(NOT BUILD_KEY_LED_ONLY)
    # App: MQTT subscriber (uses mqtt_util)
    add_executable(mqtt_sub apps/mqtt_sub.c)
    target_link_libraries(mqtt_sub mqtt_util)

    # App: MQTT publisher (uses mqtt_util)
    add_executable(mqtt_pub apps/mqtt_pub.c)
    target_link_libraries(mqtt_pub mqtt_util)
endif()
